package com.cetcs.kmga.dataManager.util;

import com.cetc.cloud.kmga.util.DateUtils;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * JSON操作工具类
 *
 * @author xutao
 * @version V1.0 创建时间：2017-02-25 1:26
 *          Copyright 2017 by CETC
 */
public class JsonUtil {

    private static Log log = LogFactory.getLog("JsonUtil");

    private static final String JSON_ERROR_CODE = "500";
    private static final String JSON_ERROR_MSG = "处理发生异常";

    /**
     * object转json
     *
     * @param object
     * @return
     * @author xutao
     * @datetime 2017-02-25 1:27
     */
    public static String objectToJson(Object object) {
        String targetJson = "";
        try {
            ObjectMapper mapper = ObjectMapperManager.getInstance();
            mapper.setDateFormat(new SimpleDateFormat(DateUtils.DATE_FORMAT_2));
            mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
                @Override
                public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException,
                        JsonProcessingException {
                    jg.writeString("");
                }
            });
            targetJson = mapper.writeValueAsString(object);
        } catch (IOException e) {
            targetJson = dealError();
            log.error(e.getMessage(), e);
        }
        return targetJson;
    }

    /**
     * JSON 转换成LISts
     *
     * @param json
     * @param cla
     * @return
     * @author xutao
     * @datetime 2017-02-25 1:27
     */
    public static List<?> jsonToList(String json, Class<?> cla) {

        return jsonToList(json, cla, DateUtils.DATE_FORMAT_2);
    }

    /**
     * json转list
     *
     * @param json
     * @param cla
     * @return
     * @author xutao
     * @datetime 2017-02-25 1:27
     */
    public static List<?> jsonToList(String json, Class<?> cla, String dateFrmt) {
        List<?> list = null;
        try {
            ObjectMapper mapper = ObjectMapperManager.getInstance();
            mapper.setDateFormat(new SimpleDateFormat(dateFrmt));
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, cla);
            list = mapper.readValue(json, javaType);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return list;
    }


    /**
     * 将JSON字符串转换成Map
     *
     * @param json
     * @return
     * @author xutao
     * @datetime 2017-03-02 13:19
     */
    public static Map<String, Object> readJson2Map(String json) {
        try {
            if (StringUtils.isEmpty(json)) {
                return null;
            }
            ObjectMapper mapper = ObjectMapperManager.getInstance();
            mapper.setDateFormat(new SimpleDateFormat(DateUtils.DATE_FORMAT_2));
            Map<String, Object> ret = mapper.readValue(json, Map.class);
            return ret;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }


    /**
     * 此方法只能转换简单的对象
     *
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T readJson2Pojo(String json, Class<T> clazz) {
        try {
            if (StringUtils.isEmpty(json)) {
                return null;
            }
            ObjectMapper mapper = ObjectMapperManager.getInstance();
            mapper.setDateFormat(new SimpleDateFormat(DateUtils.DATE_FORMAT_2));
            T ret = mapper.readValue(json, clazz);
            return ret;
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 转换复杂的对象
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T readJson2PojoByGson(String json, Class<T> clazz) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        Gson gson = new Gson();
        T ret = gson.fromJson(json, clazz);
        return ret;

    }


    public static String objectToJsonWithFieldUpper(Object object) {
        String targetJson = "";
        try {
            ObjectMapper mapper = ObjectMapperManager.getInstance();
            mapper.setPropertyNamingStrategy(new org.codehaus.jackson.map.PropertyNamingStrategy.PropertyNamingStrategyBase() {
                @Override
                public String translate(String input) {
                    return input.toUpperCase();
                }
            });
            mapper.setDateFormat(new SimpleDateFormat(DateUtils.DATE_FORMAT_2));
            mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
                @Override
                public void serialize(Object value, JsonGenerator jg, SerializerProvider sp) throws IOException,
                        JsonProcessingException {
                    jg.writeString("");
                }
            });
            targetJson = mapper.writeValueAsString(object);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return targetJson;
    }

    private static String dealError() {
        return String.format("{\"%s\": \"%s\",\"%s\":\"%s\"}", "code", JSON_ERROR_CODE, "message",
                JSON_ERROR_MSG);
    }

}
